package com.epam.qanda.web.servlet.logged;

import java.io.IOException;
import java.sql.Timestamp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;

import com.epam.qanda.db.model.Question;
import com.epam.qanda.db.model.User;
import com.epam.qanda.db.service.QuestionService;

public class AddQuestionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.sendRedirect(request.getHeader("referer"));
	}

	private String codeTag(String t) {
		String text = t;
		text = text.replaceAll("\\[code\\]",
				"<p><span class='label label-default'>Code</span></p><pre><code>");
		text = text.replaceAll("\\[/code\\]", "</pre></code>");
		return text;
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int categoryId = Integer.parseInt(request.getParameter("categoryId"));
		User user = (User) request.getSession().getAttribute("user");
		String title = request.getParameter("questionTitle");
		String text = request.getParameter("questionText");

		title = StringEscapeUtils.escapeHtml4(title);

		text = StringEscapeUtils.escapeHtml4(text);
		text = codeTag(text);

		Question question = new Question();
		question.setCategoryId(categoryId);
		question.setTitle(title);
		question.setText(text);
		question.setLikes(0);
		question.setTime(new Timestamp(System.currentTimeMillis()));
		question.setUserId(user.getId());
		new QuestionService().create(question);
		response.sendRedirect(request.getHeader("referer"));
	}
}
